import request from '@/utils/http'

// 定义响应数据类型
interface UserInfo {
  id: number
  name: string
  email: string
  role: string
}

interface LoginResponse {
  token: string
  refreshToken: string
  userInfo: UserInfo
}

// 用户登录
export const login = async (username: string, password: string) => {
  try {
    const response = await request.post<LoginResponse>('/auth/login', { username, password })

    // 处理两种可能的返回类型
    const apiResponse = 'data' in response && 'status' in response ? response.data : response

    if (apiResponse.success) {
      // 保存认证信息
      request.setAuthTokens(apiResponse.data.token, apiResponse.data.refreshToken)

      // 保存用户信息到sessionStorage
      session.set('userInfo', apiResponse.data.userInfo)

      return apiResponse.data
    } else {
      throw new Error(apiResponse.message)
    }
  } catch (error) {
    console.error('登录失败:', error)
    throw error
  }
}

// 用户登出
export const logout = async () => {
  try {
    // 调用登出API
    await request.post('/auth/logout')
  } catch (error) {
    console.error('登出API调用失败:', error)
  } finally {
    // 无论API是否成功，都清除本地存储的认证信息
    request.clearAuthTokens()
  }
}

// 获取用户信息（使用缓存）
export const getUserInfo = () => {
  return request.get<UserInfo>(
    '/user/info',
    {},
    {
      cache: true,
      cacheDuration: 5 * 60 * 1000, // 5分钟缓存
    },
  )
}

// 更新用户信息
export const updateUserInfo = (data: Partial<UserInfo>) => {
  return request.put<UserInfo>('/user/info', data)
}

// 上传用户头像
export const uploadAvatar = (file: File) => {
  return request.uploadFile<{ avatarUrl: string }>('/user/avatar', file, 'avatar')
}

// 使用可取消的请求
export const searchUsers = (keyword: string) => {
  const controller = request.createRequestController()

  const search = () =>
    request.get<UserInfo[]>('/users/search', { keyword }, { signal: controller.signal })

  return {
    execute: search,
    cancel: controller.abort,
  }
}

// 下载用户报表
export const downloadUserReport = () => {
  return request.downloadFile('/reports/users', {}, 'user_report.xlsx')
}

// 检查认证状态
export const checkAuthStatus = () => {
  if (!request.isAuthenticated()) {
    // 重定向到登录页或显示登录弹窗
    return false
  }
  return true
}

export const createUser = async (userData) => {
  return request.post('/user', userData)
}
/**
 * 请求用户信息
 */
export const getLoginInfo = async () => {
  return request.get('/user/login')
}
/**
 * 请求验签信息
 */
export const getJsapiSignature = async (data: any) => {
  return request.get('/mfmp-shop-manage/api/app/wx/getJsapiSignature', data)
}
